package com.dzsw.netty.websocket;

import com.dzsw.netty.websocket.protocal.CProtocol;
import com.dzsw.netty.websocket.util.ProtobufUtil;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Sharable
public class BinaryFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {

	public final static BinaryFrameHandler INSTANCE = new BinaryFrameHandler();

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame frame) throws Exception {
		byte[] data = ByteBufUtil.getBytes(frame.content());
		CProtocol.Message message = CProtocol.Message.parseFrom(data);
		if(message.hasHeartbeat()) {
			ctx.fireChannelRead(message.getHeartbeat());
			return;
		}
		if(message.hasRequest()) {
			ctx.fireChannelRead(message.getRequest());
			return;
		}
		if(message.hasResponse()) {
			ctx.fireChannelRead(message.getResponse());
			return;
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		log.warn("exceptionCaught ->" + ctx.channel().remoteAddress(), cause);
		ctx.channel().close();
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		CProtocol.Message message = ProtobufUtil.createHeartbeat();
		ctx.channel().writeAndFlush(message);
	}
}
